package com.haizhi.crm.biz.dao;

import com.haizhi.crm.biz.model.BrowseCountDo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.List;

/**
 * Created by yangyijun on 2018/5/10.
 */
@Repository
public interface BrowseCountDao extends JpaRepository<BrowseCountDo, Long> {
    /**
     * 添加
     *
     * @param entityType
     * @param entityKey
     */
    @Modifying
    @Query(value = "insert into tb_browse_count(entity_type, entity_key, counts, updated_dt) " +
            " values (:entityType, :entityKey, :counts, now() )", nativeQuery = true)
    void insertBrowseCount(@Param("entityType" ) String entityType, @Param("entityKey" ) String entityKey, @Param("counts" ) int counts);

    /**
     * 修改浏览次数
     *
     * @param counts
     * @param id
     */
    @Modifying
    @Query(value = "update tb_browse_count set counts=:counts  where id=:id", nativeQuery = true)
    void updateCounts(@Param("counts" ) int counts, @Param("id" ) Long id);


    /**
     * 条件查询
     *
     * @param entityType
     * @param entityKey
     * @return
     */
    @Query("select  bc from BrowseCountDo bc  where bc.entityType=:entityType and bc.entityKey=:entityKey " )
    BrowseCountDo queryByCondition(@Param("entityType" ) String entityType, @Param("entityKey" ) String entityKey);


    @Query(value = "select new com.haizhi.crm.biz.model.BrowseCountDo" +
            "(entityType,entityKey,counts) from BrowseCountDo  where entityType=:entityType order by counts desc" )
    List<BrowseCountDo> findByEntityType(@Param("entityType" ) String entityType);

    @Query(value = "select entity_key from tb_browse_count  where entity_type=:entityType and created_dt >:startDate order by counts desc limit 5", nativeQuery = true)
    List<String> findEntityKeysBy(@Param("entityType" ) String entityType, @Param("startDate" ) Date startDate);

    @Query(value = "select entity_key from tb_browse_count  where entity_type=:entityType order by counts desc limit 5", nativeQuery = true)
    List<String> findEntityKeysBy(@Param("entityType" ) String entityType);
}
